package offer;

/**
 * 请实现一个函数，把字符串中的每个空格替换成“%20”。例如输入“We are happy"，则输出”We%20are%20happy"。
 * 说明：在网络编程中，如果URL参数中含有特殊字符，如：空格、“#”等，可能导致服务器端无法获得正确的参数值。
 * 我们需要将这些特殊符号转换成服务器识别的字符。转换规则是在“%”后面跟上ASCII码的两位十六进制的表示
 * 。比如：空格的ASCII码是32，即十六进制的0x20，因此空格被替换成“%20”
 */
public class q05 {

    public static void main(String[] args) {
        String s = "We are happy";
        System.out.println(replaceSpace2(s));
        System.out.println(replaceSpace(s));
        String s1 = "how are you my name is happy";
        System.out.println(replaceSpace2(s1));
        System.out.println(replaceSpace(s1));
        String s2 = "We   are   happy  .";
        System.out.println(replaceSpace2(s2));
        System.out.println(replaceSpace(s2));
    }

    /**
     * O(n2)复杂度
     * @param s
     * @return
     */
    private static String replaceSpace(String s) {

        if (s == null || s.length() == 0) {
            return null;
        }

        StringBuilder replaceString = new StringBuilder();
        for (int i=0; i<s.length(); i++) {
            if (s.charAt(i) == ' ') {
                replaceString.append("%20");
            } else {
                replaceString.append(s.charAt(i));
            }
        }
        return replaceString.toString();
    }


    private static String replaceSpace2(String s) {

        int spaceCount = 0;
        int oldLength = s.length();
        for (int i = 0; i<oldLength;i++) {
            if (s.charAt(i) == ' ') {
                spaceCount++;
            }
        }
        System.out.println("空格数量:" + spaceCount);
        int newLength = oldLength + spaceCount * 2;

        char[] chars = new char[newLength];

        while (oldLength > 0) {
            char c = s.charAt(oldLength - 1);
            if (c == ' ') {
                chars[--newLength] = '0';
                chars[--newLength] = '2';
                chars[--newLength] = '%';
            } else {
                chars[--newLength] = c;
            }
            oldLength--;
        }

        return new String(chars);
    }

}
